package cn.minhx.mw.dtp.sdk.trigger.listener;

import cn.minhx.mw.dtp.sdk.domain.DynamicThreadPoolService;
import cn.minhx.mw.dtp.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.minhx.mw.dtp.sdk.registry.Registry;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.listener.MessageListener;

import java.util.List;

@Slf4j
public class ThreadPoolConfigAdjustListener implements MessageListener<ThreadPoolConfigEntity> {

    private final DynamicThreadPoolService dynamicThreadPoolService;
    private final Registry registry;

    public ThreadPoolConfigAdjustListener(DynamicThreadPoolService dynamicThreadPoolService, Registry registry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = registry;
    }

    @Override
    public void onMessage(CharSequence charSequence, ThreadPoolConfigEntity config) {
        try {
            log.info("[动态线程池-配置更新消息监听器]收到配置更新消息 topic={} config={}", charSequence, JSON.toJSONString(config));
            dynamicThreadPoolService.updateThreadPoolConfig(config);
            // 更新后上报最新数据
            List<ThreadPoolConfigEntity> newConfigList = dynamicThreadPoolService.getThreadPoolConfigList();
            registry.reportThreadPoolConfigList(newConfigList);
            ThreadPoolConfigEntity newConfig = dynamicThreadPoolService.getThreadPoolConfigByName(config.getThreadPoolName());
            registry.reportThreadPoolConfig(newConfig);
            log.info("[动态线程池-配置更新消息监听器]上报最新配置完成 newConfigList={} newConfig={}", JSON.toJSONString(newConfigList), JSON.toJSONString(newConfig));
        } catch (Exception e) {
            // todo 将消费失败的数据写入到redis并发送通知
            log.error("[动态线程池-配置更新消息监听器]配置更新异常 topic={} config={}", charSequence, JSON.toJSONString(config), e);
        }
    }

}
